﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Bpms.Data;
using Bpms.Entity;
using Bpms.Log;
using Bpms.Cache;

namespace Bpms.Bll
{
    public class Organization
    {
        #region Member

        /// <summary>
        /// 数据库改动事件委托
        /// </summary>
        public delegate void DBChangedEventHandler();

        /// <summary>
        /// 日志事件委托
        /// </summary>
        public delegate void LogEventHandler();

        /// <summary>
        /// 数据库改动事件
        /// </summary>
        public static event DBChangedEventHandler DBChanged;

        /// <summary>
        /// 写日志事件
        /// </summary>
        public static event LogEventHandler WriteLog;

        #region Private

        private static IDataProvider provider = DatabaseProvider.GetInstance();

        /// <summary>
        /// 数据改动事件处理函数
        /// </summary>
        static void OnDBChanged()
        {
            if (DBChanged != null)
            {
                DBChanged();
            }
        }

        /// <summary>
        /// 写日志处理函数
        /// </summary>
        static void OnWriteLog()
        {
            if (WriteLog != null)
            {
                WriteLog();
            }
        }

        #endregion

        #endregion

        /// <summary>
        /// 添加组织（部门、团队）
        /// </summary>
        /// <param name="organization">组织对象（部门、团队）</param>
        /// <returns>-1：存在相同的记录（部门名称与团队名称分开判断，即部门名称和团队名称可以相同），0：添加失败，1：添加成功</returns>
        public static int InsertOrganization(OrganizationInfo organization)
        {
            if (provider.OrganizationExists(organization, OperateType.Insert))
            {
                return -1;
            }

            if (provider.InsertOrganization(organization))
            {
                OnDBChanged();
                OnWriteLog();
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// 修改组织（部门、团队）
        /// </summary>
        /// <param name="organization">组织对象（部门、团队）</param>
        /// <returns>-1：存在相同的记录（部门名称与团队名称分开判断，即部门名称和团队名称可以相同），0：修改失败，1：修改成功</returns>
        public static int UpdateOrganization(OrganizationInfo organization)
        {
            if (provider.OrganizationExists(organization, OperateType.Update))
            {
                return -1;
            }

            if (provider.UpdateOrganization(organization))
            {
                OnDBChanged();
                OnWriteLog();
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// 删除组织（部门、团队）
        /// </summary>
        /// <param name="organizationId">组织对象（部门、团队）ID</param>
        /// <returns>删除是否成功（true：成功，false：失败）</returns>
        public static bool DeleteOrganization(int organizationId)
        {
            if (provider.DeleteOrganization(organizationId))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 判断某组织名称是否存在
        /// </summary>
        /// <param name="organization">组织对象（部门、团队）</param>
        /// <param name="operateType">判断的类型（添加或修改）</param>
        /// <returns>组织名称是否存在（true：已存在，false：不存在）</returns>
        public static bool OrganizationExists(OrganizationInfo organization, OperateType operateType)
        {
            return provider.OrganizationExists(organization, operateType);
        }

        /// <summary>
        /// 得到组织（部门、团队）对象
        /// </summary>
        /// <param name="organizationId">组织（部门、团队）ID</param>
        /// <returns>组织对象</returns>
        public static OrganizationInfo GetOrganization(int organizationId)
        {
            return provider.GetOrganization(organizationId);
        }

        /// <summary>
        /// 得到组织（部门、团队）对象列表
        /// </summary>
        /// <param name="pageId">当前页ID</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="condition">提取的条件</param>
        /// <param name="organizationType">提取的组织类型（部门或团队）</param>
        /// <returns>组织对象列表</returns>
        public static IList<OrganizationInfo> GetOrganizations(int pageId, int pageSize, string condition, OrganizationType organizationType)
        {
            IList<OrganizationInfo> organizations = null;

            CacheContext cache = CacheContext.GetCacheService(new DefaultCache());

            if (pageId == 1)
            {   // 仅为第一页时才从缓存中读取数据
                if (organizationType == OrganizationType.部门)
                {   // 读取缓存中的“部门”列表
                    organizations = cache.RetrieveObject(Cache.CacheKey.DepartmentList.ToString()) as IList<OrganizationInfo>;
                    if (organizations == null)
                    {
                        organizations = provider.GetOrganizations(pageId, pageSize, condition, organizationType);
                        cache.AddObject(Cache.CacheKey.DepartmentList.ToString(), organizations);
                    }
                }
                else if (organizationType == OrganizationType.团队)
                {   // 读取缓存中的“团队”列表
                    organizations = cache.RetrieveObject(Cache.CacheKey.TeamList.ToString()) as IList<OrganizationInfo>;
                    if (organizations == null)
                    {
                        organizations = provider.GetOrganizations(pageId, pageSize, condition, organizationType);
                        cache.AddObject(Cache.CacheKey.TeamList.ToString(), organizations);
                    }
                }
            }
            else
            {   // 从数据库中读取数据
                organizations = provider.GetOrganizations(pageId, pageSize, condition, organizationType);
            }

            return organizations;
        }

        /// <summary>
        /// 得到组织（部门、团队）对象列表
        /// </summary>
        /// <param name="condition">提取的条件</param>
        /// <returns>组织对象列表</returns>
        public static IList<OrganizationInfo> GetOrganizations(string condition)
        {
            return provider.GetOrganizations(condition);
        }

        /// <summary>
        /// 为团队分配联系人
        /// </summary>
        /// <param name="organizationId">团队ID</param>
        /// <param name="contactIdList">分配的联系人列表</param>
        /// <returns>操作是否成功（true：成功，false：失败）</returns>
        public static bool DistributeContact(int organizationId, string[] contactIdList)
        {
            if (provider.DistributeContact(organizationId, contactIdList))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 得到组织（部门、团队）名称
        /// </summary>
        /// <param name="organizationId">组织（部门、团队）ID</param>
        /// <returns>组织名称</returns>
        public static string GetOrganizationName(int organizationId)
        {
            return provider.GetOrganizationName(organizationId);
        }
    }
}
